package org.jeecg.modules.zcgl.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccqtgb.sxp.partner.security.MessageProcess;
import com.ccqtgb.sxp.partner.security.bo.RequestData;
import com.ccqtgb.sxp.partner.security.bo.ResponseData;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.properties.config.CCQTGBPropertyConfig;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.HttpClientUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.api.utils.ApiDataUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.zcgl.entity.CcqtgbLog;
import org.jeecg.modules.zcgl.entity.PublicAccountTransactionInquiry;
import org.jeecg.modules.zcgl.entity.PublicAccountTransactionInquiryDetails;
import org.jeecg.modules.zcgl.enums.CcqtgbLogTypeEnum;
import org.jeecg.modules.zcgl.enums.YesNoEnum;
import org.jeecg.modules.zcgl.mapper.PublicAccountTransactionInquiryMapper;
import org.jeecg.modules.zcgl.service.ICcqtgbLogService;
import org.jeecg.modules.zcgl.service.IPublicAccountTransactionInquiryDetailsService;
import org.jeecg.modules.zcgl.service.IPublicAccountTransactionInquiryService;
import org.jeecg.modules.zcgl.vo.PublicAccountTransactionInquiryItemsResultVO;
import org.jeecg.modules.zcgl.vo.PublicAccountTransactionInquiryPostVO;
import org.jeecg.modules.zcgl.vo.PublicAccountTransactionInquiryResultVO;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 对公账户交易明细记录
 * @Author: jeecg-boot
 * @Date: 2021-02-01
 * @Version: V1.0
 */
@Service
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class PublicAccountTransactionInquiryServiceImpl extends ServiceImpl<PublicAccountTransactionInquiryMapper, PublicAccountTransactionInquiry> implements IPublicAccountTransactionInquiryService {

    @Autowired
    private CCQTGBPropertyConfig ccqtgbPropertyConfig;
    @Autowired
    private ICcqtgbLogService ccqtgbLogService;
    @Autowired
    private IPublicAccountTransactionInquiryDetailsService inquiryDetailsService;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void publicAccountTransactionInquiryByDepart(SysDepart depart, Date date) {

        try {
            if (depart == null) {
                throw new JeecgBootException("公司没有，更新失败！");
            }
            if (StringUtils.isBlank(depart.getPartnerNo())) {
                throw new JeecgBootException("公司没有商户号，更新失败！");
            }
            if (StringUtils.isBlank(depart.getAccountNo())) {
                throw new JeecgBootException("公司没有商户对公账号，更新失败！");
            }
            CcqtgbLog log = ccqtgbLogService.selectByCompanyIdAndSucceedAndDateAndType(depart.getId(), null, date, CcqtgbLogTypeEnum.PUBLIC_ACCOUNT.getStatus());
            if (log == null) {
                log = new CcqtgbLog();
                log.setPageNo(0);
            } else if (YesNoEnum.YES.getStatus() == log.getIzSucceed().intValue()) {
                return;
            }

            String key =  "PublicAccountTransactionInquiry:" + DateUtils.yyyyMMdd.get().format(date) + ":" + depart.getId();
            //预防频繁请求，如果有值就表示前面有请求，当次不请求。
            if (redisUtil.get(key) != null){
                return;
            }

            //当前页和总的页数
            int currentPage = log.getPageNo();
            //组装请求数据
            PublicAccountTransactionInquiryPostVO vo = new PublicAccountTransactionInquiryPostVO();
            vo.setAccountno(depart.getAccountNo());
            vo.setPartner(depart.getPartnerNo());
            vo.setTransTime(DateUtils.yyyyMMdd.get().format(date));
//                    this.a(vo, depart);
            boolean bool = false;
//            if (true){return;}
            do {
                ++currentPage;
                vo.setPageNo(String.valueOf(currentPage));
                ResponseData<String> messageCallBack = MessageProcess.getResponseMessageCallBack(vo,
                        vo.getPartner(), ccqtgbPropertyConfig.getPrivateKeyPath(), ccqtgbPropertyConfig.getAesKey(),
                        null, 200, "");
                //发送post请求
                String resultString = HttpClientUtil.doPostJson(ccqtgbPropertyConfig.getPublicAccountTransactionInquiry(), JSON.toJSONString(messageCallBack));
                //预防频繁请求，设置值
                redisUtil.set(key, true, 100);
                //返回结果解密
//                    RequestData<Map> dataReslt = ApiDataUtils.getRequestData(resultString, Map.class);
//                    System.out.println(JSON.toJSONString(dataReslt));

                RequestData<PublicAccountTransactionInquiryResultVO> dataReslt = ApiDataUtils.getRequestData(resultString, PublicAccountTransactionInquiryResultVO.class);
                PublicAccountTransactionInquiryResultVO resultVO = dataReslt.getBody();
                if ("0000".equalsIgnoreCase(resultVO.getRetcode())) {
//                    bool = this.saveByVo(resultVO, log, date, depart);
                    bool = ((PublicAccountTransactionInquiryServiceImpl) AopContext.currentProxy()).saveByVo(resultVO, log, date, depart);
                } else {
                    throw new JeecgBootException(resultVO.getRetshow() + "(" + resultVO.getRetcode() + ")");
                }
                try {
                    TimeUnit.SECONDS.sleep(90);
                } catch (InterruptedException ie) {

                }
            } while (bool);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(depart.getDepartName() + "查询对公账户交易明细记录下载失败：【" + e.getMessage() + "】");
        }
    }

    @Transactional
    @Override
    public boolean saveByVo(PublicAccountTransactionInquiryResultVO resultVO, CcqtgbLog log, Date date, SysDepart depart) {
        PublicAccountTransactionInquiry inquiry = new PublicAccountTransactionInquiry();
        inquiry.setDate(date);
        Integer pageCount = Integer.valueOf(resultVO.getPageCount());
        if (pageCount.intValue() < 1) {
            inquiry.setPageNo(0);
            inquiry.setTotalNum(0);
        } else {
            inquiry.setPageNo(Integer.valueOf(resultVO.getPageNo()));
            inquiry.setTotalNum(Integer.valueOf(resultVO.getTotalNum()));
        }
        inquiry.setPageCount(pageCount);
        inquiry.setRetCode(resultVO.getRetcode());
        inquiry.setRetShow(resultVO.getRetshow());
        inquiry.setCompanyId(depart.getId());
        inquiry.setSysOrgCode(depart.getOrgCode());
        boolean bool = super.saveOrUpdate(inquiry);
        if (bool && resultVO.getInfomationDetial() != null && resultVO.getInfomationDetial().size() > 0) {
            List<PublicAccountTransactionInquiryDetails> detailsList = new ArrayList<>();
            List<PublicAccountTransactionInquiryItemsResultVO> infomationDetial = resultVO.getInfomationDetial();
            infomationDetial.stream().forEach(detialVo -> {
                PublicAccountTransactionInquiryDetails details = new PublicAccountTransactionInquiryDetails();
                details.setDate(date);
                details.setPublicAccountTransactionInquiryId(inquiry.getId());
                details.setTradeTime(Integer.valueOf(detialVo.getTradeTime()));
                details.setTradeDate(detialVo.getTradeDate());
                Date tradeDateTime = DateUtils.parseDate(detialVo.getTradeDate());
                tradeDateTime = DateUtils.nextSecond(tradeDateTime, details.getTradeTime());
                details.setTradeDateTime(tradeDateTime);
                details.setTradeNo(detialVo.getTradeNo());
                details.setAccountNo(detialVo.getAccountNo());
                details.setOtherAccAo(detialVo.getOtherAccNo());
                details.setOtherName(detialVo.getOtherName());
                details.setOtherOpenNo(detialVo.getOtherOpenNo());
                details.setTranAmt(new BigDecimal(detialVo.getTranAmt()));
                details.setMemo(detialVo.getMemo());
                details.setDrcrFlag(detialVo.getDrcrFlag());
                details.setAccBal(new BigDecimal(detialVo.getAccBal()));
                details.setCompanyId(inquiry.getCompanyId());
                details.setSysOrgCode(inquiry.getSysOrgCode());
                detailsList.add(details);
            });
            inquiryDetailsService.saveBatch(detailsList);
        }
        bool = inquiry.getPageCount().intValue() > inquiry.getPageNo().intValue();
        log.setType(CcqtgbLogTypeEnum.PUBLIC_ACCOUNT.getStatus());
        log.setPageCount(inquiry.getPageCount());
        log.setPageNo(inquiry.getPageNo());
        log.setIzSucceed(bool ? YesNoEnum.NO.getStatus() : YesNoEnum.YES.getStatus());
        log.setDate(date);
        log.setCompanyId(depart.getId());
        log.setSysOrgCode(depart.getOrgCode());
        ccqtgbLogService.saveOrUpdate(log);
        return bool;
    }
}
